package dp.mobile.entity.tower;

import java.util.HashMap;

import org.w3c.dom.Node;

import android.util.Log;

import dp.mobile.system.Utilities;
import dp.mobile.system.XMLReader;

public class TowerFactory {
	private static final String TAG = "Tower Factory";
	protected TowerFactory() {
		//Initialize
		mBuffDictionary		= new HashMap<Integer, Node>();
		mTowerDictionary	= new HashMap<Integer, TowerData>();
		
		//Load tower file
		Node root = XMLReader.instance().parseXML(Utilities.TOWERDATA_FILE);
		Log.d(TAG, "root equal? " + root.getNodeName());
		//For each child
		int childCount = root.getChildNodes().getLength();
		for (int i = 0; i < childCount; i++) {
			//Get child
			Node child = root.getChildNodes().item(i);

			//Check name
			if (child.getNodeName().equals("tower")) {
				//Prepare variable
				int j		= 0;
				int Index	= -1;

				//Check index
				int grandChildCount = child.getChildNodes().getLength();
				while (j < grandChildCount && Index < 0) {
					//Is it index?
					Node property = child.getChildNodes().item(j);
					if (property.getNodeName().equals("index"))
						Index = Integer.parseInt(property.getFirstChild().getNodeValue());

					//next
					j++;
				}

				//Save to dictionary
				if (Index >= 0) mTowerDictionary.put(new Integer(Index), new TowerData(child));
			}
		}
        
        //Load buffs.xml file
        root = XMLReader.instance().parseXML(Utilities.BUFFDATA_FILE);
        
        //For each child
        childCount = root.getChildNodes().getLength();
		for (int i = 0; i < childCount; i++) {
			//Get child
			Node child   = root.getChildNodes().item(i);
			if (child.getNodeType() == Node.TEXT_NODE) continue;
            
            //Insert to hashtable
            mBuffDictionary.put(Integer.valueOf(child.getAttributes().getNamedItem("index").getNodeValue()), child) ;
		}
	}
	
	public synchronized static TowerFactory instance() {
		//Create state manager if doesn't exist
		if (sInstance == null) {
            sInstance = new TowerFactory();
        }
		
        return sInstance;
	}

	public int getTowerNumber() {
		return mTowerDictionary.size() + 1;
	}
	
	public TowerData getBasicTower() {
		return getTowerData(1);
	}

	public TowerData getTowerData(int index) {
		return mTowerDictionary.get(new Integer(index));
	}

	public Node getBuffData(int index) {
		return mBuffDictionary.get(new Integer(index));
	}
	
	private HashMap<Integer, TowerData> mTowerDictionary;
	private HashMap<Integer, Node> mBuffDictionary;
	
	private static TowerFactory sInstance = null;
}
